import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/http/http_code.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/config/app_config.dart';
import 'package:flutter_09_game/http/http_export.dart';
import 'package:flutter_09_game/manager/ws_manager.dart';
import 'package:flutter_09_game/utils/loading/loading_utils.dart';
import 'package:flutter_09_game/utils/log/utils_log.dart';
import 'package:flutter_09_game/utils/shared/shared_export.dart';

class Application {
  static final Application _instance = Application._();

  factory Application() => _instance;

  Application._();

  Future initialize() async {
    SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);

    SystemChrome.setEnabledSystemUIMode(
      SystemUiMode.manual,
      overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom],
    );

    // 系统底部控制栏的颜色
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      systemNavigationBarColor: AppColor.navBarBackground,
      statusBarColor: Colors.transparent,
      statusBarIconBrightness: Brightness.light,
    ));
    await _configureFirebase();

    await LoadingUtils.setup();
    await SharedStorage().initShareStorage();
    await initialPrivacySDK();
    LoadingUtils.setup();

    // 检查登录状态并自动连接WebSocket
    // initializeWebSocket();
  }

  // /// 初始化WebSocket连接
  // void initializeWebSocket() {
  //   WsManager().onStateChange = (status) {
  //     clog('WsManager  onStateChange $status');
  //   };
  //
  // }

  // static bool isNeedConfig = true;

  // static String initialRoute() {
  //
  //   // if (AppUserManager().token.isEmpty || AppUserManager().user.value == null) {
  //   //   return AppRoutes.login;
  //   // } else {
  //     return AppRoutes.main;
  //   // }
  // }

  static void changeStatusBar(
      {Brightness statusBarIconBrightness = Brightness.dark}) {
    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarIconBrightness: statusBarIconBrightness,
    ));
  }

  /// 错误信息打印
  void logSystemError() {
    FlutterError.onError = (errorDetails) {
      clog(errorDetails, tag: "error", always: true);
    };
    PlatformDispatcher.instance.onError = (error, stack) {
      clog("$error \n ${stack.toString()}", tag: "error", always: true);
      return true;
    };
  }

  Future<void> setupHttp() async {
    await AppConfig.setup();
    // 网络请求需要行为操作的code码处理
    HttpManager().errorCodeListener = httpErrorCodeListener;
    // HttpConnectionCheck.checkNetWork();
  }

  Future<void> initialPrivacySDK() async {
    await setupHttp();
    // FlutterDeviceId().getDeviceId();
    // FlutterDeviceId
  }

  Future _configureFirebase() async {
    // firebaseAuth = FirebaseAuth.instanceFor(app: baseApp);

    FlutterError.onError = (errorDetails) {
      // FirebaseCrashlytics.instance.recordFlutterFatalError(errorDetails);
      // clog(errorDetails);
    };
    // Pass all uncaught asynchronous errors that aren't handled by the Flutter framework to Crashlytics
    PlatformDispatcher.instance.onError = (error, stack) {
      // FirebaseCrashlytics.instance.recordError(error, stack, fatal: true);
      return true;
    };

    // final googleAvailable = availability == GooglePlayServicesAvailability.success;
  }

  void httpErrorCodeListener(int? code) {
    code ??= 0;

    if ((code == HttpCode.code401 ||
        code == HttpCode.code33003 ||
        code == HttpCode.code20002 ||
        code == HttpCode.code40001)) {
      /// 未登录不触发退出登录弹窗
      AppUserManager().logout(type: 2);
    } else if (code == HttpCode.code33002 || code == HttpCode.code33001) {
      // AppUserManager().logout(type: 1);
    }
  }
}
